package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbProdAttaMapper;
import com.bwie.pojo.TbProd;
import com.bwie.pojo.TbProdAtta;
import com.bwie.service.TbProdAttaService;
import com.bwie.service.TbProdService;
import com.bwie.mapper.TbProdMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Lenovo
 * @description 针对表【tb_prod(商品表)】的数据库操作Service实现
 * @createDate 2025-06-20 18:37:50
 */
@Service
public class TbProdServiceImpl extends ServiceImpl<TbProdMapper, TbProd>
        implements TbProdService {

    @Autowired
    private TbProdMapper tbProdMapper;

    @Autowired
    private TbProdAttaMapper tbProdAttaMapper;

    @Override
    public R getProdList(PageInfoVo pageInfoVo) {
        Page<TbProd> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<TbProd> tbProdPage = tbProdMapper.getProdList(page, pageInfoVo);
        return R.ok().setData(tbProdPage);
    }

    @Override
    public R addProd(TbProd tbProd) {
        TbProd tbProd1 = tbProdMapper.selectOne(new QueryWrapper<TbProd>().lambda().eq(TbProd::getProdName, tbProd.getProdName()));
        if (tbProd1 != null) {
            return R.error().setMsg("商品已存在");
        }
        tbProdMapper.insert(tbProd);
        return R.ok();
    }

    @Override
    public R addProdAtta(TbProdAtta tbProdAtta) {
        TbProd tbProd = tbProdMapper.selectById(tbProdAtta.getProdId());
        if (tbProd == null) {
            return R.error().setMsg("商品不存在");
        }

        tbProdAttaMapper.delete(new QueryWrapper<TbProdAtta>().lambda().eq(TbProdAtta::getProdId, tbProdAtta.getProdId()));

        tbProdAttaMapper.insert(tbProdAtta);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteBatchProd(List<Integer> ids) {
        tbProdMapper.deleteBatchIds(ids);

        tbProdAttaMapper.delete(new QueryWrapper<TbProdAtta>().lambda().in(TbProdAtta::getProdId,ids));

        return R.ok();
    }

    @Override
    public R deleteByProdId(Integer prodId) {
        TbProd tbProd = tbProdMapper.selectOne(new QueryWrapper<TbProd>().lambda().eq(TbProd::getProdId, prodId));
        if(tbProd==null){
            return R.error().setMsg("商品不存在");
        }
        tbProdMapper.deleteById(prodId);

        return R.ok();
    }
}




